import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from 'path';
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import _ from "lodash";

const host = process.env.TAURI_DEV_HOST;

import Inspect from 'vite-plugin-inspect';

const envResolve = (mode: any) => {
  return loadEnv(mode, process.cwd());
};

const getEnv = function (env: string) {
  return envResolve(_.last(process.argv))[env];
};
const pathResolve = (pathStr: string) => {
  return path.resolve(__dirname, pathStr);
};
const pathSrc = path.resolve(__dirname, 'src');
// https://vitejs.dev/config/
export default defineConfig(async () => ({
  plugins: [
    AutoImport({
      resolvers: [
        ElementPlusResolver(),
        IconsResolver({
          prefix: "Icon",
        }),
      ],
    }),
    Components({
      resolvers: [
        IconsResolver({
          enabledCollections: ["ep"],
        }),
        ElementPlusResolver(),
      ],
      dts: path.resolve(pathSrc, "components.d.ts"),
    }),
    createSvgIconsPlugin({
      iconDirs: [pathResolve("./src/assets/icons")],
      symbolId: "icon-[dir]-[name]",
    }),
    Icons({
      autoInstall: true,
    }),

    Inspect(),
    vue(),
  ],
  define: {
    "process.env": {},
  },
  resolve: {
    alias: {
      "@": pathResolve("./src"),
    }
  },
  // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
  //
  // 1. prevent vite from obscuring rust errors
  clearScreen: false,
  // 2. tauri expects a fixed port, fail if that port is not available
  server: {
    port: 1420,
    strictPort: true,
    host: host || false,
    hmr: host
      ? {
          protocol: "ws",
          host,
          port: 1421,
        }
      : undefined,
    watch: {
    },
  },
}));
